package common;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class FileMapping {

    public boolean open(String filePath)
    {
        _filePath = filePath;

        try {
            _file = new java.io.RandomAccessFile(filePath, "r");
            _fileSize = _file.length();

            _fileChannel = _file.getChannel();
            _mapBuffer = _fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, _fileSize);
            return true;
        }
        catch (Exception e) {
            return false;
        }
    }

    public String getFilePath() {
        return _filePath;
    }

    public long getFileSize() {
        return _fileSize;
    }

    public byte getByte(int index) {
        if (_mapBuffer != null) {
            return _mapBuffer.get(index);
        }
        return 0;
    }

    public void close() {
        if (_mapBuffer != null) {
            _mapBuffer.clear();
            _mapBuffer = null;
        }
        if (_fileChannel != null) {
            try {
                _fileChannel.close();
            }
            catch (IOException e){
            } finally {
                _fileChannel = null;
            }
        }

        if (_file != null) {
            try {
                _file.close();
            }
            catch (IOException e) {
            }
            finally {
                _file = null;
            }
        }
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        close();
    }

    private long _fileSize = 0;
    private String _filePath;

    private FileChannel _fileChannel;
    private MappedByteBuffer _mapBuffer;
    private java.io.RandomAccessFile _file;
}
